/* =============================================================
 * Your Grandmother's guide to Algorithms
 * =============================================================
 *
 * Copyright (c) 2007, Saverio Miroddi
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions are met:
 * 
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright 
 *       notice, this list of conditions and the following disclaimer in the 
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the SaverioMiroddiSoftware nor the names of its 
 *       contributors may be used to endorse or promote products derived from 
 *       this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *  
 * ---------------------------
 * HashAlgo.java
 * ---------------------------
 *
 */
package algos;

import java.util.Iterator;

import utils.Utils;



import dbobjects.Condition;
import dbobjects.tables.Table;

/**
 * Hash join algorithm.
 * <p>
 * For convention, we call the two tables "Hashed" and "Other".
 * 
 * @author Saverio Miroddi
 */
class HashAlgo implements IAlgo {
	
	private HashJoinMap<Object, String[]> hashedTable;
	private boolean hashedIsLeft;
	
	private Table otherTable;
	private int otherJoinColPos;
	
	private String[] currOtherRow;
	private Iterator<String[]> currHashedIterator;
	
	HashAlgo(Table leftTable, Table rightTable, Condition cond, int type) {
		checkParams(cond, type);
		
		/* setup tables data */
		
		int leftSize = leftTable.size(), rightSize = rightTable.size();
		
		if (leftSize < rightSize) {
			hashedIsLeft = true;
			hashedTable = doHashTable(leftTable, cond.leftPos, leftSize);

			otherTable = rightTable;
			otherJoinColPos = cond.rightPos;
		}
		else {
			hashedIsLeft = false;
			hashedTable = doHashTable(rightTable, cond.rightPos, rightSize);

			otherTable = leftTable;
			otherJoinColPos = cond.leftPos;
		}
	}
	
	private void checkParams(Condition cond, int type) {
		if (cond.operator != Condition.OP_EQ) {
			throw new IllegalArgumentException("Hash Join only accepts equal operator");
		}
		else if (type == Join.LEFT_OUTER) {
			throw new UnsupportedOperationException("Hash Join currently not supports outer joins.");
		}
	}
	
	/**
	 * Hash all the rows of the passed table in a HashJoinMap. 
	 */
	private HashJoinMap<Object, String[]> doHashTable(Table sourceTable, 
			int joinColPos, int totRows)
	{
		// FIXME bug test with 2 rows and totRows = 1 
		HashJoinMap<Object, String[]> retTable = 
			new HashJoinMap<Object, String[]>(totRows);
		
		while (sourceTable.next()) {
			String[] row = sourceTable.getRow();
			String joinValue = row[joinColPos];

			// skip null, because doesn't match equality
			if (joinValue != null) retTable.add(joinValue, row);
		}
		
		return retTable;
	}

	/**
	 * TODO: implement OUTER JOIN
	 */
	@Override
	public boolean next() {
		while (true) {
			/* if we have no iterator for Hashed (first time) or iterator
			 * for current key has no more record, move forward in Other */
			if (currHashedIterator == null || ! currHashedIterator.hasNext()) {
				if (otherTable.next()) {
					currOtherRow = otherTable.getRow();
					
					String joinKey = currOtherRow[otherJoinColPos];
					currHashedIterator = hashedTable.values(joinKey);
				}
				/* no more records in Other, return false! */
				else {
					currHashedIterator = null;
					return false;
				}
			/* Now we restart the cycle to make sure we have at least one
			 * next record in the Hashed iteratorO */
			}
			/* Hashed has a next record for the current key, return true */
			else {
				return true;
			}
		}
	}
	
	@Override
	public String[] getCurrentRow() {
		if (currHashedIterator == null) {
			throw new IllegalStateException("No current row.");
		}
		else {
			String[] hashedRow = currHashedIterator.next(); 
			String[] otherRow = otherTable.getRow();
			
			if (hashedIsLeft) return Utils.merge(hashedRow, otherRow);
			else return Utils.merge(otherRow, hashedRow);
		}
	}
}